<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\InvalidRequestException;
use App\Http\Controllers\Controller;
use App\Http\Requests\SmsRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;

class SmsController extends Controller
{
    /**
     * @param SmsRequest $request
     * @return JsonResponse
     * @throws InvalidRequestException
     */
    public function index(SmsRequest $request): JsonResponse
    {
        $phone = $request->get('phone', '');
        $type = $request->get('type', '');
        $user = User::query()->where('phone', $phone)->first();
        if ($type == 'register' && $user) {
            //注册的时候，对象必须不存在
            return failReturn('手机号已注册');
        }
        //登录找回密码，用户对象必须存在
        if (in_array($type, ['login', 'password']) && !$user) {
            return failReturn('手机号不存在');
        }
        $code = mt_rand(100000, 999999);
        sendLoginSms($phone, $code, $type);
        return successReturn();
    }
}
